using System;
using System.Collections.Generic;
using System.Threading;

namespace Mehat.San.SanFS
{
	
	public class SystemDirectory
	{
		private static IDirectory						mSysDir;
		private static IDirectory						mVmntDir;
		private static IDirectory						mPmntDir;
		private static Mutex							mVmntDirentsLock = new Mutex();
		private static Dictionary<string, IDirectory>	mVmntDirents = new Dictionary<string, IDirectory>();
		
		public static void Initialize()
		{
			mSysDir = DirEntFactory.CreateDirectory(null, (IDirectory) DirEntFactory.Root, ".System");
			mVmntDir = DirEntFactory.CreateDirectory(null, mSysDir, "Virtual Mounts");
			mPmntDir = DirEntFactory.CreateDirectory(null, mSysDir, "Physical Mounts");
			
			VirtualMountManager.Added += new VMountNotifierHandler(SystemDirectory.OnVMountAdded);
			VirtualMountManager.Removed += new VMountNotifierHandler(SystemDirectory.OnVMountRemoved);
		}
		
		private static void OnVMountAdded(IVirtualMount VMnt)
		{
			mVmntDirentsLock.WaitOne();
			try
			{
				mVmntDirents.Add(VMnt.Name, DirEntFactory.CreateDirectory(VMnt, mVmntDir, VMnt.Name));
			}
			catch
			{
			}
			finally
			{
				mVmntDirentsLock.ReleaseMutex();
			}
		}
		
		private static void OnVMountRemoved(IVirtualMount VMnt)
		{
			mVmntDirentsLock.WaitOne();
			try
			{
				IDirectory	ent = mVmntDirents[VMnt.Name];
				mVmntDirents.Remove(VMnt.Name);
				DirEntFactory.DestroyEntry((IDirectoryEntry) ent);
			}
			catch
			{
			}
			finally
			{
				mVmntDirentsLock.ReleaseMutex();
			}
		}
	}	// END CLASS
}	// END NAMESPACE
